import { gql } from '@apollo/client';
import { graphql, withApollo } from '@apollo/client/react/hoc';
import { withRouter } from 'react-router';
import { compose } from 'recompose';
import viewstateHoc from '@kuiper-components/viewstate-hoc';
import { JOB_TASK_TYPES } from '../../../common/constants';

export default compose(
	withRouter,
	withApollo,
	graphql(
		gql`
			{
				JobMany(
					filter: { verification: { isVerified: true } }
					sort: _ID_DESC
					limit: 0
				) {
					_id
					note
					targetUrl
					target {
						host
						protocol
						port
					}
				}
			}
		`,
		{ name: 'jobList' }
	),
	viewstateHoc({ name: 'jobList' }),
	graphql(
		gql`
			query($_id: MongoID!) {
				JobOne(filter: { _id: $_id }) {
					_id
					assetId
					note
					targetUrl
					target {
						host
						protocol
					}
					sourceIp
					ignoredWarnIdMap
					httpSettings{
						name
						target
						interval
					}
					pingSettings{
						name
						target
						interval
					}
					${JOB_TASK_TYPES.map(
						type => `
							${type}ResultId
							${type}PrevResultId
							${type}Result {
								_id
								name
								target
								startTime
								endTime
								result {
									warnings {
										_id
										id
										title
										level
										category
										affects
										detail
										isResolved
										ignoredTime
									}
									addition
								}
							}

							${type}PrevResult{
								_id
								name
								target
								startTime
								endTime
								result {
									warnings{
										_id
										id
										title
										level
										category
										affects
										isResolved
										ignoredTime
									}
									addition
								}
							}
						`
					)}
					asset{
						_id
						target
						result{
							_id
							target
							endTime
							result{
								warningCount
								warnings{
									_id
									level
									id
									category
									affects
									detail
									title
									isResolved
									ignoredTime
								}
							}
						}
						prevResult {
							_id
							target
							endTime
							result{
								warningCount
								warnings{
									_id
									id
									category
									affects
									detail
									title
									isResolved
									ignoredTime
								}
							}
						}
					}
				}
			}
		`,
		{
			skip: ({
				match: {
					params: { jobId },
				},
			}) => !jobId,
			options({
				match: {
					params: { jobId },
				},
			}) {
				return {
					variables: { _id: jobId },
					errorPolicy: 'all',
				};
			},
		}
	),
	viewstateHoc()
);
